package teller

import (
	"context"
	"strconv"
	"time"

	"code.bydev.io/cht/customer/kyc_admin_service/internal/pkg/config"
	"code.bydev.io/cht/customer/kyc_admin_service/internal/pkg/lark"
	"emperror.dev/errors"
	"git.bybit.com/svc/go/pkg/bzap"
	"git.bybit.com/svc/stub/pkg/pb/api/alarm"
	"go.uber.org/zap"
)

type Teller = *teller

type teller struct {
	Logger *zap.Logger
	Alarm  lark.LarkRaiser
}

var globTeller *teller

func New(logger *zap.Logger, raiser lark.LarkRaiser) Teller {
	globTeller = &teller{
		Logger: logger,
		Alarm:  raiser,
	}
	return globTeller
}
func GlobTeller(ctx context.Context, text string, err error) error {
	if globTeller == nil {
		return errors.New("teller not init")
	}
	return globTeller.KycAlarm(ctx, text, err)
}

func (t *teller) alarm(ctx context.Context, text string, err error) error {
	//  告警
	attributes := make(map[string]string)
	attributes["nowTime"] = strconv.FormatInt(time.Now().In(time.UTC).Unix(), 10)
	attributes["err"] = err.Error()
	msg := &alarm.Alarm{
		Environment: config.GetString(config.KeyAlarmEnv),
		Text:        text,
		Attributes:  attributes,
	}
	raiserErr := t.Alarm.Raise(context.Background(), msg)
	if raiserErr != nil {
		bzap.LogError(t.Logger, "alarm err", err)
	}
	return raiserErr
}

func (t *teller) KycAlarm(ctx context.Context, text string, bizErr error) error {
	return t.alarm(ctx, text, bizErr)
}
